/**
 * 文件处理页面
 */

import React, { useEffect, useState } from 'react';
import { Row, Col, Typography, Steps, Alert, Spin } from 'antd';
import styled from 'styled-components';
import { themeConfig } from '../theme/themeConfig';
import { Card } from '../components/ui/Card';
import { Button } from '../components/ui/Button';
import { ProgressDisplay } from '../components/upload/ProgressDisplay';
import { useUploadState, useProcessState, useLanguageState } from '../store/appStore';
import { FileService } from '../services/fileService';
import { ProcessProgress } from '../types';

const { Title, Paragraph } = Typography;
const { Step } = Steps;

const PageContainer = styled.div`
  min-height: 100vh;
  background-color: ${themeConfig.colors.background};
  padding: ${themeConfig.spacing.xl};
`;

const ContentContainer = styled.div`
  max-width: 1200px;
  margin: 0 auto;
`;

const HeaderSection = styled.div`
  text-align: center;
  margin-bottom: ${themeConfig.spacing.xxl};
`;

const MainTitle = styled(Title)`
  color: ${themeConfig.colors.text} !important;
  margin-bottom: ${themeConfig.spacing.md} !important;
`;

const SubTitle = styled(Paragraph)`
  color: ${themeConfig.colors.textSecondary} !important;
  font-size: ${themeConfig.typography.fontSize.body} !important;
  margin-bottom: 0 !important;
`;

const StepsContainer = styled.div`
  margin-bottom: ${themeConfig.spacing.xxl};
  
  .ant-steps-item-process .ant-steps-item-icon {
    background-color: ${themeConfig.colors.primary};
    border-color: ${themeConfig.colors.primary};
  }
  
  .ant-steps-item-finish .ant-steps-item-icon {
    background-color: ${themeConfig.colors.primary};
    border-color: ${themeConfig.colors.primary};
  }
`;

const ProcessingCard = styled(Card)`
  margin-bottom: ${themeConfig.spacing.xl};
`;

const ActionSection = styled.div`
  display: flex;
  justify-content: center;
  gap: ${themeConfig.spacing.md};
  margin-top: ${themeConfig.spacing.xl};
`;

const LoadingContainer = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  gap: ${themeConfig.spacing.md};
`;

const LoadingText = styled.div`
  font-size: ${themeConfig.typography.fontSize.body};
  color: ${themeConfig.colors.textSecondary};
`;

interface ProcessingPageProps {
  onComplete: () => void;
  onBack: () => void;
}

export const ProcessingPage: React.FC<ProcessingPageProps> = ({ onComplete, onBack }) => {
  const { uploadFile } = useUploadState();
  const { processProgress, isProcessing, setProcessProgress, setIsProcessing } = useProcessState();
  const { setLanguageFiles, setDetectionReport, setGeneratedFiles } = useLanguageState();
  const [isCompleted, setIsCompleted] = useState(false);

  useEffect(() => {
    if (uploadFile && !isCompleted) {
      processFile();
    }
  }, [uploadFile, isCompleted]);

  const processFile = async () => {
    if (!uploadFile) return;

    setIsProcessing(true);
    setIsCompleted(false);

    try {
      const result = await FileService.processFile(
        uploadFile.file,
        (progress: ProcessProgress) => {
          setProcessProgress(progress);
        }
      );

      // 保存处理结果
      setLanguageFiles(result.languageFiles);
      setDetectionReport(result.conflicts);
      setGeneratedFiles(result.generatedFiles);

      setIsCompleted(true);
      setIsProcessing(false);
    } catch (error) {
      console.error('文件处理失败:', error);
      setIsProcessing(false);
    }
  };

  const handleNext = () => {
    if (isCompleted) {
      onComplete();
    }
  };

  const handleBack = () => {
    onBack();
  };

  const getCurrentStep = () => {
    if (processProgress.status === 'completed') return 2;
    if (processProgress.status === 'error') return 1;
    if (processProgress.status === 'generating') return 2;
    if (processProgress.status === 'parsing') return 1;
    return 0;
  };

  return (
    <PageContainer>
      <ContentContainer>
        <HeaderSection>
          <MainTitle level={1}>
            处理文件
          </MainTitle>
          <SubTitle>
            正在解析Excel文件并生成语言文件...
          </SubTitle>
        </HeaderSection>

        <StepsContainer>
          <Steps current={getCurrentStep()} size="small">
            <Step title="上传文件" description="文件已上传" />
            <Step title="处理文件" description="解析数据并检测冲突" />
            <Step title="下载结果" description="获取生成的语言文件" />
          </Steps>
        </StepsContainer>

        <Row gutter={[24, 24]}>
          <Col xs={24} lg={16}>
            <ProcessingCard title="处理进度" variant="elevated">
              {isProcessing ? (
                <LoadingContainer>
                  <Spin size="large" />
                  <LoadingText>正在处理文件，请稍候...</LoadingText>
                </LoadingContainer>
              ) : (
                <ProgressDisplay progress={processProgress} />
              )}
            </ProcessingCard>
          </Col>
          
          <Col xs={24} lg={8}>
            <Card title="处理信息" variant="outlined">
              <div style={{ fontSize: themeConfig.typography.fontSize.body, lineHeight: themeConfig.typography.lineHeight.body }}>
                <p><strong>文件名：</strong>{uploadFile?.name}</p>
                <p><strong>文件大小：</strong>{uploadFile ? `${(uploadFile.size / 1024 / 1024).toFixed(2)} MB` : '未知'}</p>
                <p><strong>处理状态：</strong></p>
                <ul>
                  <li>解析Excel文件结构</li>
                  <li>提取翻译数据</li>
                  <li>检测翻译冲突</li>
                  <li>生成Dart文件</li>
                </ul>
              </div>
            </Card>
          </Col>
        </Row>

        {processProgress.status === 'error' && (
          <Alert
            message="处理失败"
            description={processProgress.error || '未知错误'}
            type="error"
            showIcon
            style={{ marginBottom: themeConfig.spacing.lg }}
          />
        )}

        <ActionSection>
          <Button
            variant="outline"
            onClick={handleBack}
            disabled={isProcessing}
          >
            返回上一步
          </Button>
          <Button
            variant="primary"
            onClick={handleNext}
            disabled={!isCompleted}
          >
            查看结果
          </Button>
        </ActionSection>
      </ContentContainer>
    </PageContainer>
  );
};
